// WebSocket模块

const socketIO = require('socket.io')
const db = require('../config/mysql.js')
const utils = require("../common/utils")

let io

const initSocket = (server) => {
  io = socketIO(server, {
    allowEIO3: true,
    cors: true
  });
  // 连接用户数量
  let count = 0
  // 连接用户
  let connections = []
  
  let intervalId = null
  
  io.on('connection', (socket) => {
    console.log("Socket connected")

    let sql = `select * from animal`
    let arr = []
    db.query(sql, (err, result) => {
      if (result.length > 0) {
        result.forEach(item => {
          arr = [...arr, {
            id: item.id,
            name: item.name,
            feed_time: item.feed_time.split(',')
          }]
        })
        arr = [...new Set(arr)]
        intervalId = setInterval(() => {
          let curTime = utils.formatDate(new Date().getTime()).split(' ')[1]
          arr.forEach(item => {
            if (item.feed_time.includes(curTime)) {
              socket.emit('message', {
                data: `<div>${curTime}点了，记得给<span style="color: red;">${item.name}</span>喂养食物哦</div>`
              });
            }
            return
          })
        }, 1000);
      }
    })

    // socket.on('testCall', (req, callback) => {
    //   let num = req.data
    //   console.log("收到的随机数：" + num);
    //   callback("随机数是：" + num + "，扩大2倍：" + num * 2)
    // })

    socket.on('disconnect', () => {
      console.log('Socket disconnected');
      clearInterval(intervalId);
    })
  })
}

module.exports = {
  initSocket
}
